package com.demo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author gy
 * @date 2022/6/15
 */
@Component
@Aspect
public class UseTimeAspect {

    private static final Logger logger = LoggerFactory.getLogger(UseTimeAspect.class);

    @Pointcut("execution(* com.demo.service..*.*(..))")
    private void webUseTime(){

    }

    @Around("webUseTime()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        // 获取目标对象
        Object target = pjp.getTarget();
        Class<?> clz = target.getClass();

        // 获取目标方法
        MethodSignature m = (MethodSignature)pjp.getSignature();
        String method = m.getMethod().getName();

        // 开始时间
        long startTime = System.currentTimeMillis();
        // 执行目标方法
        Object proceed = pjp.proceed();
        // 结束时间
        long endTime = System.currentTimeMillis();
        // 耗时
        long useTime = endTime - startTime;

        // 记录日志
        logger.info("["+clz+"]类的["+method+"]方法执行耗时["+useTime+"]毫秒");

        return proceed;
    }
}
